<template>
  <div>
    <el-form class="query-form"
      ref="queryForm"
      size="small"
      :model="queryParams"
      :inline="true">
      <el-form-item label="所属项目" prop="app_id">
        <el-select v-model="queryParams.app_id" placeholder="请选择" @change="handleQuery">
          <el-option label="全部" :value="null"/>
          <el-option v-for="item in permission_projectList" :key="item.app_id"
            :label="item.name" :value="item.app_id" />
        </el-select>
      </el-form-item>
      <el-form-item label="版本" prop="version">
        <el-input v-model="queryParams.version" placeholder="用,分割版本"/>
      </el-form-item>
      <el-form-item label="渠道" class="unionclass">
        <el-select v-model="union_ids" filterable multiple collapse-tags clearable placeholder="请选择" @change="handleQuery">
          <!-- <el-option  label="全部" :value="null" /> -->
          <el-option v-for="(item, index) in channelOptions" :key="item.channel_id+index"
            :label="`${item.name} (${item.channel_id})`" :value="item.channel_id" />
        </el-select>
      </el-form-item>
      <el-form-item label="签约名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入"  clearable
          @keyup.enter.native="handleQuery" @clear="handleQuery"/>
      </el-form-item>
      <el-form-item label="支付方式" prop="pay_type" class="small-query">
        <el-select v-model="queryParams.pay_type" placeholder="请选择" @change="handleQuery">
          <el-option label="全部" :value="null"/>
          <el-option v-for="item in payTypeOptions" :label="item.dictLabel" :value="item.dictValue" :key="item.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="签约类型" prop="sign_type" placeholder="请选择">
        <el-select v-model="queryParams.sign_type" placeholder="请选择" @change="handleQuery">
          <el-option label="全部" :value="null"/>
          <el-option label="支付并签约" value="pay_and_sign" />
          <el-option label="仅签约" value="only_sign" />
        </el-select>
      </el-form-item>
      <el-form-item label="最新周期扣费价格" class="noMax">
        <el-input-number v-model="numberRange.new_single_amount_begin"
          placeholder="最低价"
          size="small"
          :precision="2"
          style="width: 83px"/>
        -
        <el-input-number v-model="numberRange.new_single_amount_end"
          placeholder="最高价"
          size="small"
          :precision="2"
          style="width: 83px"/>
      </el-form-item>
      <el-form-item label="签约状态" prop="status"  class="small-query">
        <el-select v-model="queryParams.status" placeholder="请选择" @change="handleQuery">
          <el-option label="全部" :value="null"/>
          <el-option label="未签约" value="waited"></el-option>
          <el-option label="已签约" value="signed_success"></el-option>
          <el-option label="已解约" value="unsigned_success"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="big-query" label="创建时间" prop="createdDateRange">
        <el-date-picker v-model="createdDateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 210px;"
          @change="handleQuery">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="赠送内容" prop="unit_id">
        <el-select v-model="queryParams.unit_id" style="width: 180px;">
          <el-option value="" label="全部"></el-option>
          <el-option v-for="item in chargeUnitList" :value="item.unit_id" :label="item.internal_name" :key="item.unit_id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="unit_amount" v-show="queryParams.unit_id">
        <el-input-number v-model="queryParams.unit_amount" :min="0" :precision="0" controls-position="right" style="width: 100px;"></el-input-number>
      </el-form-item>

      <el-form-item label="搜索" prop="keyword_filed" class="noMax">
        <el-select v-model="queryParams.keyword_filed" placeholder="请选择" style="width: 120px; margin-right: 10px;">
          <el-option label="微信模板ID" value="wechat_plant_id"/>
          <el-option label="用户ID" value="user_id" />
          <el-option label="首次订单ID" value="first_order_id" />
          <el-option label="会员套餐ID" value="product_id" />
        </el-select>
        <el-input v-model="queryParams.keyword"
          placeholder="关键词"
          size="small"
          style="width:240px"
          clearable
          @keyup.enter.native="handleQuery"
          @clear="handleQuery" />
      </el-form-item>
      <el-form-item class="noMax">
        <el-button type="primary"
          size="small"
          @click="handleQuery">搜索</el-button>
        <el-button
          size="small"
          @click="resetQuery">重置</el-button>
        <el-button
          size="small"
          type="success"
          :loading="exportLoading"
          @click="exportExcel">导出全部</el-button>
          <el-button
          size="small"
          type="danger"
          @click="handleBatchUpdata"
          :disabled="multipleSelection.length <1">批量编辑</el-button>
      </el-form-item>
    </el-form>
    <el-table
      ref="multipleTable"
      v-loading="loading"
      style="margin-bottom: 15px;"
      :data="tableList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" :selectable="selectable" fixed="left"/>
      <el-table-column label="签约ID" min-width="200" prop="agreement_no"  fixed="left" />
      <el-table-column label="所属项目" width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.app_id|translateToName(permission_projectList,'app_id','name') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道" width="160" prop="union_id">
         <template #default="{ row }">
          <span>{{ row.union_id |  translateToName(channelOptions, 'channel_id', 'name')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="版本" width="120" prop="version"/>
      <el-table-column label="会员套餐ID" width="120" prop="product_id"/>
      <el-table-column label="会员套餐名称" min-width="170" prop="product_name"/>
      <el-table-column label="签约名称" min-width="170" prop="name"/>
      <el-table-column label="续费周期" width="100">
        <template slot-scope="scope">
          {{ scope.row.period }}{{ scope.row.period_type|periodTypeFilter }}
        </template>
      </el-table-column>
      <el-table-column label="原始周期扣费价格" width="170" prop="single_amount">
        <template #default = {row}>
          {{ row.currency_code | formatMoneyCode }}{{ row.single_amount | formatMoney}}
        </template>
      </el-table-column>
      <el-table-column label="最新周期扣费价格" width="170" prop="new_single_amount">
        <template #default = {row}>
          {{ row.currency_code | formatMoneyCode }}{{ row.new_single_amount | formatMoney}}
        </template>
      </el-table-column>
      <el-table-column label="赠送内容" width="170" prop="product_bus_ext">
        <template #default = {row}>
          <template v-if="row.product_bus_ext && row.product_bus_ext.gifts && row.product_bus_ext.gifts[0]">
            {{ row.product_bus_ext.gifts[0].amount }}{{ row.product_bus_ext.gifts[0].unit_id|translateToName(chargeUnitList,'unit_id','name') }}
          </template>
        </template>
      </el-table-column>
      <el-table-column label="签约类型" min-width="120">
        <template slot-scope="scope">
          {{ scope.row.sign_type ==='pay_and_sign' ? '支付并签约' : '仅签约' }}
        </template>
      </el-table-column>
      <el-table-column label="支付方式" width="100" prop="pay_type">
        <template slot-scope="scope">{{ typeFormat(scope.row) }}</template>
      </el-table-column>
      <el-table-column label="微信模板ID" min-width="170" prop="wechat_plant_id">
        <template slot-scope="scope">{{ scope.row.wechat_plant_id || '--' }}</template>
      </el-table-column>
      <el-table-column label="首次续费日期" min-width="160" prop="execute_time"/>
      <el-table-column label="下次扣费时间" min-width="160">
        <template slot-scope="scope">
          <span v-if="scope.row.next_execute_time">{{ scope.row.next_execute_time|parseTime() }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="160">
        <template slot-scope="scope">
          <span v-if="scope.row.created_at">{{ scope.row.created_at|parseTime() }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="签约时间" min-width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.signed_at|parseTime() }}</span>
        </template>
      </el-table-column>
      <el-table-column label="解约时间" min-width="160">
        <template slot-scope="scope">
          <span v-if="scope.row.unsigned_at">{{ scope.row.unsigned_at|parseTime() }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="用户ID" min-width="160" prop="user_id">
        <template  #default="{ row }">
          <el-button size="small" type="text" @click="handleUserDetail(row)">{{row.user_id}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="首次订单ID" min-width="200" prop="first_order_id"/>
      <el-table-column label="签约状态">
        <template slot-scope="scope">
          {{ scope.row.status ==='signed_success' ? '已签约' : scope.row.status ==='unsigned_success' ? '已解约' : '未签约' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" type="text" :disabled="scope.row.status!=='signed_success' || scope.row.pay_type === 5" @click="handleUpdata(scope.row)">修改</el-button>
          <el-button size="small" type="text" :disabled="scope.row.status!=='signed_success'" @click="handleUnsign(scope.row)">解约</el-button>
          <el-button size="small" type="text" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-if="total>0"
      :total="total"
      layout="total,slot,sizes,prev,pager,next,jumper"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList">
    </pagination>
    <!-- 修改对话框 start -->
    <el-dialog title="修改签约信息" :visible.sync="openUpdata" width="800px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" label-width="150px" style="display: grid;grid-template-columns: repeat(2,1fr);">
        <el-form-item v-if="!isBatchUpdata" label="签约ID">
          <el-input v-model="form.agreement_no" style="width:221px" :disabled="true"/>
        </el-form-item>
        <el-form-item label="所属项目">
          <el-select v-model="form.app_id" style="width:221px" :disabled="true">
            <el-option label="全部" :value="null"/>
            <el-option v-for="item in permission_projectList" :key="item.app_id"
              :label="item.name" :value="item.app_id" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="isBatchUpdata" label="会员套餐ID">
          <el-input v-model="form.product_id" style="width:221px" :disabled="true"/>
        </el-form-item>
        <el-form-item v-if="!isBatchUpdata" label="权益包名称">
          <el-input v-model="form.attr_name" style="width:221px" :disabled="true"/>
        </el-form-item>
        <el-form-item label="签约状态">
          <el-input v-model="form.statusName" style="width:221px" :disabled="true"/>
        </el-form-item>
        <template v-if="!isBatchUpdata">
          <el-form-item label="签约名称">
            <el-input v-model="form.name" style="width:221px" :disabled="true"/>
          </el-form-item>
          <el-form-item label="续费周期">
            <el-input v-model="form.period" style="width:221px" :disabled="true"/>
          </el-form-item>
        </template>

        <el-form-item label="原始周期扣费价格">
          <el-input v-model="form.single_amount" style="width:221px" :disabled="true"/>
        </el-form-item>
        <el-form-item label="最新周期扣费价格">
          <el-input-number v-model="form.new_single_amount" :precision="2" :min="0.01" :max="form.single_amount"></el-input-number>
        </el-form-item>

        <template v-if="!isBatchUpdata">
          <el-form-item label="支付方式">
            <el-input v-model="form.sign_type_name" style="width:221px" :disabled="true"/>
          </el-form-item>
          <el-form-item label="签约创建时间">
            <el-input v-model="form.signed_at" style="width:221px" :disabled="true"/>
          </el-form-item>
        </template>

        <template v-if="form.product_bus_ext && form.product_bus_ext.gifts">
          <div style="grid-column: 1 / 3;" class="modules-title">
            <span>赠送配置（非必填）</span>
          </div>
          <el-form-item label="权益配置">
            <el-row>
              <el-col :span="18">
                <el-form-item prop="product_bus_ext.gifts[0].unit_id">
                  <el-select v-model="form.product_bus_ext.gifts[0].unit_id" style="width: 160px;">
                    <el-option v-for="item in chargeUnitList" :value="item.unit_id" :label="item.internal_name" :key="item.unit_id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="product_bus_ext.gifts[0].amount">
                  <el-input-number v-model="form.product_bus_ext.gifts[0].amount" :min="0" :precision="0" controls-position="right" style="width: 100px;"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="使用期限" prop="product_bus_ext.gifts[0].duration" key="product_bus_ext.gifts[0].duration">
            <el-select v-model="form.product_bus_ext.gifts[0].duration" placeholder="请选择" :disabled="!form.product_bus_ext.gifts[0].amount">
              <el-option v-for="(item, index) in memberTimeOptions" :key="index" :label="item[1]" :value="item[0]"/>
            </el-select>
          </el-form-item>
          <!-- <div style="grid-column: 1 / 3;">
            <el-form-item label="赠送描述" prop="product_bus_ext.gifts[0].desc">
              <el-input v-model="form.product_bus_ext.gifts[0].desc" @blur="form.product_bus_ext.gifts[0].desc=$event.target.value.trim()" :disabled="!form.product_bus_ext.gifts[0].amount"/>
            </el-form-item>
          </div> -->
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="openUpdata = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog title="详情" :visible.sync="open" width="700px" :close-on-click-modal="false">
      <agreementDetail :agreementInfo="agreementInfo" :payTypeOptions="payTypeOptions" :channelOptions="channelOptions" @handleUserDetail="handleUserDetail" :chargeUnitList="chargeUnitList" :memberTimeOptions="memberTimeOptions"/>
    </el-dialog>
    <el-dialog title="用户详情" :visible.sync="userOpen" width="700px" :close-on-click-modal="false" top="5vh">
      <userDetail :userInfo="userInfo" :channelOptions="channelOptions"/>
    </el-dialog>
    <AuthCode ref="AuthCode" :visible.sync="openAuth" :title="authTitle" :authObj="authObj" @submit="submitSendCode"/>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Axios from 'axios'
import AuthCode from '@/components/auth-code'
import userDetail from '@/views/user/components/user-detail.vue'
import { listAgreement, unsignAgreement, createExportAgreementTask, queryExportAgreementTask, getAgreementGroup, batchUpdateAgreement, updateAgreement } from '@/api/agreement/agreement'
import { getChannelByAppId } from '@/api/system/channel'
import { getUser } from '@/api/user/user'
import { getChargeUnit } from '@/api/system'
// import { sendCode } from '@/api/member/product'
import { formatMoney, parseTime, toFixed } from '@/utils'
import agreementDetail from './components/agreement-detail.vue'
import { getMemberValidTime } from '@/constants/constant'
export default {
  name: 'Agreement',
  components: { AuthCode, agreementDetail, userDetail },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 总金额
      orderAmounts: 0,
      // 权益表格数据
      tableList: null,
      // 渠道选择
      channelOptions: [],
      payTypeOptions: [],
      multipleSelection: [],
      userTypeOptions: [],
      // 计费单位
      chargeUnitList: [],
      // 会员等级选项
      memberTimeOptions: undefined,
      // 是否显示弹出层
      authTitle: '',
      openAuth: false,
      open: false,
      openUpdata: false,
      isBatchUpdata: false,
      // 表单参数
      authObj: {},
      agreementInfo: {},
      userInfo: {},
      userOpen: false,
      // 查询参数 - 创建时间
      createdDateRange: [],
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        app_id: null,
        version: '',
        union_id: null,
        name: '',
        pay_type: null,
        sign_type: null,
        status: 'signed_success',
        keyword_filed: 'wechat_plant_id',
        keyword: '',
        unit_id: '',
        unit_amount: null
      },
      union_ids: [],
      // 修改参数
      form: {},
      // 查询数字区间参数
      numberRange: {
        new_single_amount_begin: undefined,
        new_single_amount_end: undefined
      },
      exportLoading: false
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList'])
  },
  filters: {
    periodTypeFilter (val) {
      switch (val) {
        case 'DAY':
          return '天'
        case 'MONTH':
          return '月'
        default:
          return ''
      }
    }
  },
  created () {
    this.memberTimeOptions = getMemberValidTime()
    const list = this.permission_projectList.map(item => item.app_id)
    Axios.all([this.getListApi(), getChannelByAppId({ app_ids: list.join(',') })]).then(Axios.spread((res1, res2) => {
      this.channelOptions = res2.data.list
      this.tableList = res1
    }))
    this.getDicts('pay_method').then(res => {
      this.payTypeOptions = (res.data || []).map(item => {
        item.dictValue = parseInt(item.dictValue) || 0
        return item
      })
    })
    this.getDicts('user_account_type').then(res => {
      this.userTypeOptions = res.data || []
    })

    getChargeUnit().then(res => {
      this.chargeUnitList = (res.data.list || [])
    })
  },
  methods: {
    getListApi () {
      this.mergeQueryParams()
      this.loading = true
      return new Promise((resolve, reject) => {
        const params = Object.assign({}, this.queryParams)
        if (!params.unit_id) {
          delete params.unit_id
          delete params.unit_amount
        }
        listAgreement(params).then(response => {
          const data = response.data || {}
          // eslint-disable-next-line no-unused-expressions
          data.list?.forEach(it => {
            if (it.product_bus_ext) {
              try {
                it.product_bus_ext = JSON.parse(it.product_bus_ext)
              } catch (e) {
                //
              }
            }
            if (!it.product_bus_ext) {
              it.product_bus_ext = {}
            }
          })
          resolve(data.list)
          this.orderAmounts = data.order_amounts || []
          this.total = data.count || 0
        }).finally(() => {
          this.loading = false
        })
      })
    },
    /** 查询用户列表 */
    getList () {
      this.getListApi().then(res => {
        this.tableList = res
      })
    },
    // 支付方式内置字典翻译
    typeFormat (row, column) {
      return this.selectDictLabel(this.payTypeOptions, row.pay_type)
    },
    /** 搜索按钮操作 */
    handleQuery () {
      let { queryParams, numberRange } = this
      Object.keys(numberRange).forEach(key => {
        const item = numberRange[key]
        this.queryParams[key] = item ? item * 100 : undefined
      })
      const isValid = this.validNumberRangeInput(queryParams, 'new_single_amount_begin', 'new_single_amount_end')
      if (!isValid) {
        this.msgError('请检查数字区间输入')
        return
      }
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      // const now = parseTime(new Date(), '{y}-{m}-{d}')
      this.createdDateRange = []
      this.union_ids = []
      Object.keys(this.numberRange).forEach(key => {
        this.numberRange[key] = undefined
      })
      this.queryParams.keyword = ''
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 解约-点击
    handleUnsign (row) {
      this.authObj = {
        type: 'unsign_agreement',
        data: {
          agreement_no: row.agreement_no,
          user_id: row.user_id
        }
      }
      this.authTitle = `确定将签约${row.agreement_no}进行解约吗？验证码通过验证后才可进行操作`
      this._sendCode()
    },
    // 修改-点击
    handleUpdata (row) {
      let product_bus_ext = row.product_bus_ext ? JSON.parse(JSON.stringify(row.product_bus_ext)) : {}
      if (!product_bus_ext.gifts) {
        product_bus_ext.gifts = [
          {
            type: 'charge',
            unit_id: null,
            unit_name: null,
            amount: null,
            duration: null,
            desc: null
          }
        ]
      }
      this.form = {
        ...row,
        statusName: row.status === 'signed_success' ? '已签约' : row.status === 'unsigned_success' ? '已解约' : '未签约',
        period: row.period + this.$options.filters['periodTypeFilter'](row.period_type),
        single_amount: Number(formatMoney(row.single_amount)),
        new_single_amount: Number(formatMoney(row.new_single_amount)),
        sign_type_name: row.sign_type === 'pay_and_sign' ? '支付并签约' : '仅签约',
        signed_at: parseTime(row.signed_at),
        product_bus_ext
      }
      this.openUpdata = true
      this.isBatchUpdata = false
    },
    // 批量修改-点击
    handleBatchUpdata () {
      this.mergeQueryParams()
      const params = Object.assign({}, this.queryParams)
      params.ids = [...this.multipleSelection]
      const new_single_amount = this.tableList.filter(v => v.id === params.ids[0])[0]?.new_single_amount
      delete params.page
      delete params.page_size
      getAgreementGroup({ filter: params })
        .then(response => {
          const { group_by_info } = response.data || {}
          let product_bus_ext
          try {
            product_bus_ext = JSON.parse(group_by_info.product_bus_ext)
          } catch (e) {
            product_bus_ext = {}
          }
          if (!product_bus_ext.gifts) {
            product_bus_ext.gifts = [
              {
                type: 'charge',
                unit_id: null,
                unit_name: null,
                amount: null,
                duration: null,
                desc: null
              }
            ]
          }
          this.form = {
            app_id: group_by_info.app_id,
            product_id: group_by_info.product_id,
            statusName: group_by_info.status === 'signed_success' ? '已签约' : group_by_info.status === 'unsigned_success' ? '已解约' : '未签约',
            single_amount: Number(formatMoney(group_by_info.single_amount)),
            new_single_amount: Number(formatMoney(new_single_amount)),
            product_bus_ext
          }
          this.openUpdata = true
          this.isBatchUpdata = true
        })
        .catch(e => {
          this.$confirm('勾选的批量编辑的项的所属项目、权益包名称、签约名称、签约状态（已签约），原始周期扣费价格，赠送内容、使用期限、赠送描述须保持一致，当前有不一致，请重新勾选！', '提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'warning'
          }).catch(() => {})
        })
    },
    // 修改||批量修改-弹窗确定
    submitForm () {
      if (this.isBatchUpdata) {
        this.mergeQueryParams()
        const params = Object.assign({}, this.queryParams)
        params.ids = [...this.multipleSelection]
        delete params.page
        delete params.page_size
        this.authObj = {
          type: 'batch_update_agreement',
          data: {
            filter: JSON.stringify(params),
            new_single_amount: toFixed(this.form.new_single_amount * 100, 0)
          }
        }
      } else {
        this.authObj = {
          type: 'update_agreement',
          data: {
            agreement_id: this.form.id,
            new_single_amount: toFixed(this.form.new_single_amount * 100, 0)
          }
        }
      }
      if (this.form.product_bus_ext.gifts[0].amount) {
        if (!this.form.product_bus_ext.gifts[0].unit_id) {
          this.$message.error('赠送配置中的计费单位不能为空！')
          return
        }
        if (!this.form.product_bus_ext.gifts[0].duration) {
          this.$message.error('赠送配置中的使用期限不能为空！')
          return
        }
        // if (!this.form.product_bus_ext.gifts[0].desc) {
        //   this.$message.error('赠送配置中的赠送描述不能为空！')
        //   return
        // }
        this.form.product_bus_ext.gifts[0].unit_name = this.$options.filters.translateToName(this.form.product_bus_ext.gifts[0].unit_id, this.chargeUnitList, 'unit_id', 'name')
        this.authObj.data.product_bus_ext = JSON.stringify(this.form.product_bus_ext)
      }
      this.openUpdata = false
      this.authTitle = `确定要修改签约信息吗？验证码通过验证后才可进行操作`
      this._sendCode()
    },
    _sendCode () {
      this.openAuth = true
      // 点击发送才调用接口
      // sendCode(this.authObj).then(res => {
      //   if (res.data.need_verify) {
      //     this.openAuth = true
      //   } else {
      //     this.submitSendCode({
      //       code: res.data.code,
      //       vid: res.data.vid
      //     })
      //   }
      // })
    },
    submitSendCode (codeObj) {
      if (this.authObj.type === 'unsign_agreement') {
        this._unsignAgreement(codeObj)
      } else if (this.authObj.type === 'update_agreement') {
        this._updateAgreement(codeObj)
      } else if (this.authObj.type === 'batch_update_agreement') {
        this._batchUpdateAgreement(codeObj)
      }
    },

    // 调用解约接口
    _unsignAgreement (codeObj) {
      unsignAgreement(this.authObj.data, codeObj).then(() => {
        this.$message({
          type: 'success',
          message: '解约成功!'
        })
        this.openAuth = false
        this.getList()
      }).catch(e => {
        this.$refs.AuthCode.cancelLoading()
      })
    },

    // 调用修改签约信息接口
    _updateAgreement (codeObj) {
      updateAgreement(this.authObj.data, codeObj).then(() => {
        this.$message({
          type: 'success',
          message: '修改成功!'
        })
        this.openAuth = false
        this.getList()
      }).catch(e => {
        this.$refs.AuthCode.cancelLoading()
      })
    },

    // 调用批量修改签约信息接口
    _batchUpdateAgreement (codeObj) {
      const params = {
        new_single_amount: this.authObj.data.new_single_amount,
        filter: JSON.parse(this.authObj.data.filter),
        product_bus_ext: this.authObj.data.product_bus_ext
      }
      batchUpdateAgreement(params, codeObj).then(() => {
        this.$message({
          type: 'success',
          message: '批量修改成功!'
        })
        this.openAuth = false
        this.getList()
      }).catch(e => {
        this.$refs.AuthCode.cancelLoading()
      })
    },

    /** 查看详情 */
    handleDetail (row) {
      this.agreementInfo = row
      this.open = true
    },

    /** 点击-全部导出 */
    exportExcel () {
      this.exportLoading = true
      this.mergeQueryParams()
      const params = Object.assign({}, this.queryParams)
      delete params.page
      delete params.page_size
      createExportAgreementTask({ filter: params })
        .then(response => {
          const { task_id } = response.data || {}
          if (task_id) {
            this.queryExportTask(task_id, () => {
              this.exportLoading = false
            })
          } else {
            this.$message.error('导出订单任务创建失败')
            this.exportLoading = false
          }
        })
        .catch(e => {
          this.exportLoading = false
        })
    },
    // 表格勾选
    handleSelectionChange (val) {
      this.multipleSelection = val.map(item => item.id)
    },
    selectable (row, index) {
      if (row.status !== 'signed_success' || row.pay_type === 5) {
        return false
      }
      return true
    },
    /** 查询导出订单任务结果 */
    queryExportTask (task_id, func) {
      queryExportAgreementTask({ task_id })
        .then(response => {
          if (response.data?.status === 'finished') {
            const link = document.createElement('a')
            link.href = response.data.file_url
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            typeof func === 'function' && func(true)
          } else {
            setTimeout(() => {
              this.queryExportTask(task_id, func)
            }, 1000)
          }
        })
        .catch(() => {
          typeof func === 'function' && func(false)
        })
    },

    /** 合并列表搜索条件 */
    mergeQueryParams () {
      let { createdDateRange } = this
      const signedDate = this.addDateRange(createdDateRange, 'created_at_begin', 'created_at_end')
      signedDate.created_at_begin = new Date(signedDate.created_at_begin)
      signedDate.created_at_end = new Date(signedDate.created_at_end)
      Object.assign(this.queryParams, signedDate, { union_id: this.union_ids.join(',') })
    },

    userTypeFormat (row, column) {
      return this.selectDictLabel(this.userTypeOptions, row.reg_type)
    },
    /** 用户查看详情 */
    handleUserDetail (row) {
      // this.loading = true
      if (!row.auth_id) {
        return
      }
      getUser(row.auth_id).then(response => {
        const data = response.data
        data.reg_types = this.userTypeFormat(data)
        this.userInfo = data
        this.userOpen = true
      }).finally(() => {
        // this.loading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-table-column--selection .cell {
  padding-left: 10px;
}
.query-form .el-form-item.noMax {
  max-width: none;
}
.unionclass /deep/ .el-tag.el-tag--info {
  max-width: 118px;
  text-overflow: ellipsis;
  overflow: hidden;
  .el-tag__close {
    display: none;
  }
}
</style>
